package gitee

import (
	"context"
	"fmt"
	"gitee.com/openeuler/go-gitee/gitee"
	"github.com/antihax/optional"
	"github.com/openshift-pipelines/pipelines-as-code/pkg/params/info"
)

func (v *Provider) IsAllowed(ctx context.Context, runevent *info.Event) (bool, error) {
	if v.Client == nil {
		return false, fmt.Errorf("no github client has been initialized, " +
			"exiting... (hint: did you forget setting a secret on your repo?)")
	}
	if v.checkMembership(ctx, runevent, v.user) {
		return true, nil
	}
	return false, nil

}

func (v *Provider) IsAllowedOwnersFile(ctx context.Context, runevent *info.Event) (bool, error) {
	//TODO implement me
	panic("implement me")
}

func (v *Provider) CheckPolicyAllowing(ctx context.Context, runevent *info.Event, i []string) (bool, string) {
	//TODO implement me
	panic("implement me")
}

func (v *Provider) checkMembership(ctx context.Context, runevent *info.Event, user *gitee.UserHook) bool {
	opts := &gitee.GetV5ReposOwnerRepoCollaboratorsUsernamePermissionOpts{AccessToken: optional.NewString(runevent.Provider.Token)}
	permission, _, err := v.Client.RepositoriesApi.GetV5ReposOwnerRepoCollaboratorsUsernamePermission(ctx, v.owner, runevent.Repository, user.Name, opts)
	if err != nil {
		return false
	}

	// 账号仓库是管理员，说明有权限管理
	if err == nil && permission.Permission == "admin" {
		return true
	}
	return false
}
